﻿#region Imports

using System;
using bGallery.Core.Common;
using bGallery.Core.Data;
using Spring.DataBinding;
using Spring.Validation;

#endregion

namespace bGallery.Web
{
	/// <summary>
	/// Registration page
	/// </summary>
	public partial class Registration : Page
	{
		#region Private Fields
		private Core.Domain.User user;
		private IValidator userValidator;
		private IUserDao userDao;
		#endregion

		#region Properties
		/// <summary>
		/// User who is trying to register
		/// </summary>
		public Core.Domain.User RegisteringUser
		{
			get { return user; }
			set { user = value; }
		}

		/// <summary>
		/// Sets validator of user
		/// </summary>
		public IValidator UserValidator
		{
			set { userValidator = value; }
		}

		/// <summary>
		/// Sets UserDao which is used to check 
		/// conflicts and save new user
		/// </summary>
		public IUserDao UserDao
		{
			set { userDao = value; }
		}
		#endregion

		#region Model Management and Data Binding Methods
		protected override void InitializeModel()
		{
			user = new Core.Domain.User();
		}

		protected override void LoadModel(object savedModel)
		{
			user = (Core.Domain.User)savedModel;
		}

		protected override object SaveModel()
		{
			return user;
		}

		protected override void InitializeDataBindings()
		{
			BindingManager.AddBinding("tbName.Text", "RegisteringUser.Name");
			BindingManager.AddBinding("tbSurname.Text", "RegisteringUser.Surname");
			BindingManager.AddBinding("tbEmail.Text", "RegisteringUser.Email");
			BindingManager.AddBinding("tbUsername.Text", "RegisteringUser.Username");
			BindingManager.AddBinding("@(TextUtil).GetMd5Hash(tbPassword.Text)", "RegisteringUser.Password", BindingDirection.SourceToTarget);
		}
		#endregion

		#region Event Handlers
		/// <summary>
		/// Returns to home home page after click on cancel
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void ReturnHome(object sender, EventArgs e)
		{
			SetResult("HomePage");
		}

		/// <summary>
		/// Saves user
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void Save(object sender, EventArgs e)
		{
			if (Validate(this, userValidator))
			{
				userDao.Save(user);
				SetResult("RegistrationLogin");
			}
		}

		#endregion

		#region Public functions
		/// <summary>
		/// Checks if user with same name already exists
		/// </summary>
		/// <returns></returns>
		public bool UsernameExists()
		{
			return userDao.Exists(user.Username);
		}
		#endregion
	}
}
